package com.haoxi.gateway.util.db;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

import com.haoxi.gateway.common.InitGatewayConfig;

import sun.jdbc.rowset.CachedRowSet;

/**
 * @author Cloud
 * @version 1.1
 */

public class DBConnectUtil {
	private static final Log log = LogFactory.getLog(DBConnectUtil.class);
	
	/**
	 * DB config file path
	 */
	private static final String CONIG_FILE_PATH = "database.xml";
	
	/**
	 * default data name
	 */
	private static String DEFAULT_DATA_NAME = "sms";
	
	/**
	 * datasource map
	 */
	private static HashMap dsMap;
	
	static {
		init();
	}
	
	/**
	 * init data source
	 */
	private synchronized static void init() {//���еĶ�ȡ�����ļ� database.xml
		try {
			dsMap = new HashMap();
			
			log.debug("begin setup DataBase Source......");
			 InputStream in = InitGatewayConfig.class
             .getResourceAsStream("/"+CONIG_FILE_PATH);
			//File filepath = new File(CONIG_FILE_PATH);
		
			//log.debug("config file path:"+filepath.getAbsolutePath());
			long lTime = System.currentTimeMillis();
			DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
			Configuration conf = builder.build(in);//buildFromFile(filepath);
			Configuration[] confs = conf.getChildren();
			for (int i = 0; i < confs.length; i++) {
				BaseData dataSource = new BaseData(confs[i]);
				dsMap.put(dataSource.getName(), dataSource);
			}
			log.debug("Setup END !!! time:"+(System.currentTimeMillis()-lTime));
		} catch (ConfigurationException e) {
			log.error("db config error:" + e);
		} catch (IOException e) {
			log.error("db config file error:" + e);
		} catch (SAXException e) {
			log.error("db config sax error:" + e);
		}
	}
	
	 /**
     * ��ѯ����
     * @param sql
     * @return
     * @throws SQLException
     */
    public static ResultSet executeCachedQuery(String sSQL, String dataName) throws SQLException {
        CachedRowSet cachedrowset = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rset = null;
        try {
            conn = open(dataName);
            stmt = conn.createStatement();
            rset = stmt.executeQuery(sSQL);
            cachedrowset = new CachedRowSet();
            cachedrowset.populate(rset);
        } catch (Exception exception) {
            log.error("executeQuery:" + exception + ":" + sSQL);
        } finally {
            if (null != rset) {
                try {
                    rset.close();
                } catch (SQLException e) {
                    log.error("close ResultSet error:" + e);
                }
                rset = null;
            }
            if (null != stmt) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    log.error("close Statement error:" + e);
                }
                stmt = null;
            }
            if (null != conn) {
                try {
                    conn.close();
                } catch (Exception e) {
                    log.error("close Connection error:" + e);
                }
            }
            else{
                log.error("connection is null !!!");
            }
        }
        return cachedrowset;
    }

    /**
     * ���²���
     * @param sql
     * @throws SQLException
     */
    public static int executeUpdate(String sSQL, String dataName) throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        int rows = 0;
        try {
            conn = open(dataName);
            stmt = conn.createStatement();
            rows = stmt.executeUpdate(sSQL);
        } catch (Exception exception) {
            log.error("executeUpdate:" + exception + ":" + sSQL);
        } finally {
        	if (null != stmt) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    log.error("close Statement error:" + e);
                }
                stmt = null;
            }
            if (null != conn) {
                try {
                    conn.close();
                } catch (Exception e) {
                    log.error("close Connection error:" + e);
                }
            }
            else{
                log.error("connection is null !!!");
            }
        }
        return rows;
    }
    
    /**
     * ��� data �����ֲ�����ݿ�l��
     * @param data name
     * @return
     * @throws SQLException
     */
    public static Connection open(String dataName) throws SQLException {
        if(dsMap != null) {
        	Object obj = null;
        	if(dataName == null || "".equals(dataName.trim())) {
        		obj = dsMap.get(DEFAULT_DATA_NAME);
                if(obj instanceof BaseData) {
                    return ((BaseData)obj).getConnection();
                }
        	} else {
        		obj = dsMap.get(dataName);
                if(obj instanceof BaseData) {
                    return ((BaseData)obj).getConnection();
                }
        	}
        }
        return null;
    }
}